//
//  DeviceUpdateViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/27.
//

import UIKit
import SVProgressHUD
import iOSDFULibrary
import SwiftyJSON
import VTO2Lib

class DeviceUpdateViewController: RViewController  {

    /// 已经是最新版本
    @IBOutlet weak var latestVersionLabel: UILabel!
    /// 最新版本详情
    @IBOutlet weak var latestVersionDescLabel: UILabel!
    /// 更新按钮
    @IBOutlet weak var updateBtn: UIButton!
    @IBOutlet weak var updateBtnBg: UIImageView!
    /// 最新版本
    var newLatestVer = "1.1"
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = hexColor("F9F9F9")!
        
        self.latestVersionLabel.layer.cornerRadius = 8
        self.latestVersionLabel.layer.masksToBounds = true
        
        
        guard let info = RManager.manager.info else { return }
        
        // 查看是否最新版本
        let url = String(format: "https://update.checkmering.jp/device/firmware/latestversion?SerialNo=%@", info.sn)
        SVProgressHUD.show()
        let service = FBYHomeService.init()
        service.searchMessage("get", andWithDic: ["":""], andUrl: url) { result in
            SVProgressHUD.dismiss()
            
            let jsData = result.data(using: .utf8)
            let resultInfo = try! JSONSerialization.jsonObject(with: jsData!, options: .allowFragments) as! NSDictionary
            
            let resultVer = resultInfo["firmwareLatestVer"] as? String ?? "1.1"
            self.newLatestVer = resultVer
            
            // 已经是最新版本
            if CompareVersion.compareVersion2(info.software, to: resultVer) == 0 {
                self.needUpdate(need: false)
                self.latestVersionLabel.text = "最新バージョン:v\(resultVer)"
            }else {
                // 需要更新
                self.needUpdate(need: true)
                self.latestVersionDescLabel.text = "最新バージョン:v\(resultVer)アップデート内容:デバイスファームウェアを更新"
            }
        } andFailure: { error in
            SVProgressHUD.dismiss()
            self.needUpdate(need: false)
            self.latestVersionLabel.text = "最新バージョン:v\(info.software)"
        }

    }
    
    func needUpdate(need: Bool) {
        self.latestVersionLabel.isHidden = need
        self.latestVersionDescLabel.isHidden = !need
        self.updateBtn.isHidden = !need
        self.updateBtnBg.isHidden = !need
        if need == false {
            if let info = RManager.manager.info {
                self.latestVersionLabel.text = "最新バ-ジョンです。\nバ-ジョン:v\(info.software)"
            }
        }
    }
    
    /// 更新按钮点击事件
    @IBAction func updateBtnDidClicked(_ sender: UIButton) {
        
        guard let info = RManager.manager.info else { return }
        
        SVProgressHUD.show()
        
        // 下载
        let downLoadManager = DownloadTaskTool()
        downLoadManager.downUrl = "https://update.checkmering.jp/device/firmware/download?SerialNo=\(info.sn)&Ver=\(info.software)"
        let savePath = DocumentFunction.downloadDirectory(path: "download") + "aaa.zip"
        downLoadManager.savePath = savePath
        // 更新下载进度
        downLoadManager.progressBlock = { (progress) in
            OperationQueue.main.addOperation {
                print("下载进度：\(progress)")
                
                // 下载完成
                if progress == 1.0 {
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                        SVProgressHUD.dismiss()
                        self.initDFUService(path: savePath)
                    }
                }
                
            }
        }
        //开始下载
        downLoadManager.start()
        
    }
    
    func initDFUService(path: String) {
        
//        let path = Bundle.main.path(forResource: "CMRing", ofType: "zip")!
        
        guard let device = RManager.manager.currentDevice else { return }
        SVProgressHUD.show()
        VTBLEUtils.sharedInstance().delegate = self
        VTO2Communicate.sharedInstance().delegate = self
        let eventQueue = DispatchQueue(label: "com.ota.updater")
        let initiator = DFUServiceInitiator.init(queue: eventQueue, delegateQueue: eventQueue, progressQueue: eventQueue, loggerQueue: eventQueue)
        var data = Data.init()
        try! data = Data.init(contentsOf: URL.init(fileURLWithPath: path))
        let selectedFirmware = DFUFirmware.init(zipFile: data)!
        initiator.with(firmware: selectedFirmware)
        initiator.alternativeAdvertisingNameEnabled = true
        initiator.logger = self
        initiator.delegate = self
        initiator.progressDelegate = self
        initiator.start(target: device.rawPeripheral)
        
    }
    
    
}

extension DeviceUpdateViewController: VTO2CommunicateDelegate, VTBLEUtilsDelegate {
    
    func didDiscover(_ device: VTDevice) {
        let identifier = device.rawPeripheral.identifier.uuidString
        if identifier == RManager.manager.currentDevice?.identifiers {
            VTBLEUtils.sharedInstance().stopScan()
            VTBLEUtils.sharedInstance().connect(to: device)
        }
    }

    func didConnectedDevice(_ device: VTDevice) {
        VTO2Communicate.sharedInstance().peripheral = device.rawPeripheral
        VTO2Communicate.sharedInstance().delegate = self
    }

    func serviceDeployed(_ completed: Bool) {
        if completed {
            VTO2Communicate.sharedInstance().beginGetInfo()
        }else {
            SVProgressHUD.dismiss()
        }
    }
    
    func getInfoWithResultData(_ infoData: Data?) {
        guard let infoData = infoData else { return }
        RManager.manager.info = VTO2Parser.parseO2Info(with: infoData)
        SVProgressHUD.dismiss()
        self.needUpdate(need: false)
    }
    
}

/// 更新蓝牙版本
extension DeviceUpdateViewController: LoggerDelegate, DFUServiceDelegate, DFUProgressDelegate {
    func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) {
        // 进度
        let currentProgress = Float(progress) / Float(totalParts) / 100.0
        SVProgressHUD.showProgress(currentProgress)
        print("当前进度:\(currentProgress)")
    }
    
    
    // 更新状态
    func dfuStateDidChange(to state: DFUState) {
        print("DFUState state\(state)")
        if state == .completed {
            
            // 更新完成 同步远程
            guard let info = RManager.manager.info else { return }
            let url = String(format: "https://update.checkmering.jp/device/firmware/register?SerialNo=%@&Ver=%@", info.sn, self.newLatestVer)
            let service = FBYHomeService.init()
            service.searchMessage("get", andWithDic: ["":""], andUrl: url) { result in
                
            } andFailure: { error in
                
            }
            
            // 再重新链接一次
            VTBLEUtils.sharedInstance().startScan()
            
        }
    }
    
    func dfuError(_ error: DFUError, didOccurWithMessage message: String) {
        SVProgressHUD.dismiss()
        print("升级失败error:\(error) message:\(message)")
    }
    
    
    // 日志打印
    func logWith(_ level: LogLevel, message: String) {
        print("日志打印level:\(level) message:\(message)")
    }
}
